<?php

namespace App\Http\Controllers\UserCenter;

use App\Eloquent\User;
use App\Admin\Eloquent\Code;
use App\Admin\Eloquent\OrganizationalUser;
use App\Eloquent\Information;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\SetNameRequest;
use App\Http\Requests\SetPhoneNumberRequest;
use App\Http\Requests\ModifyPasswordRequest; 
use App\Http\Requests\BindingBankCardRequest; 
use App\Http\Requests\UnbindingBankCardRequest; 
use App\Extensions\Pagination\BoosstrapPageUser;
use App\Eloquent\TradeRecords;
use App\Eloquent\Projects;
use CreateHostingDeposit;
use CreateHostingWithdraw;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use SetRealName;
use Illuminate\Support\Facades\Cache;
use BindingVerify;
use SetPayPassword;
use QueryIsSetPayPassword;
use BindingBankCard;
use BindingBankCardAdvance;
use UnbindingVerify;
use UnbindingBankCard;
use UnbindingBankCardAdvance;
use ModifyPayPassword;
use FindPayPassword;
use ModifyVerifyMobile;
use App\Admin\Eloquent\GiftActivity;
use App\Eloquent\Article;
use Log;
use CreateHostingTransfer;

/**
 * 用户中心控制器
 *
 * Class UserCenterController
 */
class UserCenterController extends Controller
{
    /**
     * 返回用户个人中心 密码
     */
    public function index()
    {
        $user = User::user();
        $user->sendPaymentMoney();
        // return $user->transferToSavingPot();
        
          if($user->hasRole('GuaranteeAgency')){
            //跳转至担保机构页面
            return redirect()->action('UserCenter\GuaranteeController@index',['menu'=>11]);
        }

        $user->checkRole('User');
        $user = User::user();

//        sendEmailValidateCode("961510893@qq.com");
        $securityLevel = 10;

        //判断用户是否验证邮箱
        if ($user->email_verified == 0 ) {
            $emailValidate = false;
        } else {
            $emailValidate = true;
            //获取并处理用户邮箱
            $user_email = $user->email;
            $index = strrpos($user_email, '@');
            $user_email = substr($user_email, 0, 3) . "*******" . substr($user_email, ($index - 2));
            //等级加15
            $securityLevel += 15;
        }

        //判断用户是否验证手机号码
        if ($user->phone_number_verified == 0) {
            $phoneNumberValidate = false;
        } else {
            $phoneNumberValidate = true;
            //处理手机号码
            $phone_number = $user->phone_number;
            $phone_number = substr($phone_number, 0, 3) . '*****' . substr($phone_number, 8);
            $securityLevel += 15;
        }

        //判断用户是否验证身份证
        if ($user->userInfo->name_verified == 0) {
            $idCardValidate = false;
        } else {
            $securityLevel += 20;
            $idCardValidate = true;
            $id_card = $user->userInfo->id_card;
            $id_card = substr($id_card, 0, 4) . '**********' . substr($id_card, 14);
        }

        //判断用户绑定银行卡
        if(!empty($user->userInfo->bank_card_number)){
            $securityLevel += 20;
        }

        //判断是否设置支付密码
        // $result = QueryIsSetPayPassword::send(['identity_id'=> $user->identity_id, 'identity_type' => 'UID']);

            $isSetPayPassword = 0;
        if($user->isSetPayPassword()){
            $isSetPayPassword = 1;
            $securityLevel += 20;

            //发送注册红包
            //
        }

        return view('web.user_center.user_settings', compact('securityLevel', 'emailValidate', 'phoneNumberValidate', 'idCardValidate', 'user_email', 'phone_number', 'id_card' ,'isSetPayPassword'));
    }

    /**
     * 资产总览
     * @return mixed
     */
    public function center(){
        $user = User::user();
        if($user->hasRole('Loaner')){
            return redirect()->action('UserCenter\LoanerController@index',['menu'=>1]);
        }   
        $user->checkRole('User');

        $menu = 1;

        //查询用户最近投资的项目
        $projects = DB::table('projects as a')->select('a.projects_name', 'a.id', 'a.projects_file', 'a.status', 'a.trade_repayment_date', 'a.trade_finish_date', 'b.expected_return','b.invest_time', 'b.invest_money')->leftJoin('projects_user as b', 'a.id', '=', 'b.projects_id')
            ->where('b.user_id',User::user()->id)
            ->orderBy('b.invest_time','desc')
            ->paginate(4);
        return view('web.user_center.user_center',compact('projects'));
    }

    /**
     * 红包查询
     * 
     * @param  int|integer $type [description]
     * @return [type]            [description]
     */
    public function gift(int $type = 0){
        $user = User::user();
        $user->checkRole('User');
        // $menu = 2;

        //查询所有红包
        $gifts = DB::table('gift_activities as a')
        ->select('a.name','a.used_rule_money','b.begin_time','b.status','b.end_time', 'b.money', 'b.use_time', 'a.used_rule')->leftJoin('gift_receives as b', 'a.id', '=', 'b.activity_id')
            ->where('b.user_id', User::user()->id);

        if($type == 1){ //为使用
            $gifts = $gifts->where('b.status', 0);
        }elseif ($type == 2){   //一使用
            $gifts = $gifts->where('b.status', 1);
        }elseif($type == 3){
            //Todo 查询已失效红包
            $gifts = $gifts->where('b.status', 2);
        }

        $gifts=$gifts->paginate(7);
        return view('web.user_center.gift',compact('type','gifts'));
    }   

    /**
     * 邀请有礼
     *
     * @return string
     */
    public function invitation(){
        $user = User::user();
        $user->checkRole('User');

        //生成投资人的推广链接
        $link = "https://".$_SERVER['SERVER_NAME'].'/invitation/'.$user->userInfo->invite_code;

        //查询用户获得的红包奖励
        $money = (DB::select('select sum(invite_money) as money from user_info where recommended = '.$user->id))[0]->money;
        //查询用户的好友注册人数
        $count = (DB::select('select count(user_id) as count from user_info where recommended = '.$user->id))[0]->count;

        //查询用户好友投资人数
        $count2 = (DB::select('select count(distinct(a.user_id)) as count from projects_user as a inner join user_info as b on a.user_id = b.user_id where b.recommended = '.$user->id))[0]->count;

        //查询用户好友投资记录
        $data = DB::table('user_info as a')
            ->leftJoin('users as b', 'a.user_id', '=', 'b.id')
            ->leftJoin('projects_user as c', 'c.user_id', '=','b.id')
            ->where('a.recommended', '=', $user->id)
            ->groupBy('a.user_id')
            ->select(DB::raw('b.phone_number_verified,a.name, b.username, b.email, b.created_at,b.phone_number,a.invite_money,count(c.user_id) as count'))
            ->paginate(5);

        return view('web.user_center.invitation',compact('link', 'data', 'money', 'count', 'count2'));
    }

    /**
     * 充值记录
     * 
     * @param  Request $request    [description]
     * @param  int     $query_type [description]
     * @return [type]              [description]
     */
    public function rechargeRecord(Request $request){
        $user = User::user();
        $user->checkRole('User');
        $query = $request->only('status','startTime','endTime');

        //查询充值记录
        $data = DB::table('trade_records')
                ->where('pay_user', $user->id)
                ->where('type', 4)
                ->select('sn', 'created_at','pay_time', 'card_number', 'money', 'status');

        //追加查询条件
        if(!empty($query['status'])){
            if($query['status'] == 'Y'){
                $data = $data->where('status', '1');
            }elseif($query['status'] == 'N'){
                $data = $data->where('status', '0');
            }else{
                $data = $data->where('status', '-1');
            }
        }

        if(!empty($query['startTime'])){
            $data = $data->where('created_at', '>=', $query['startTime']);
        }

        if(!empty($query['endTime'])){
            $data = $data->where('created_at', '<=', $query['endTime']);
        }

        //分页
        $data = $data->paginate(10);
        //获取分页链接
        $links = (new BoosstrapPageUser($data))->render();
        return view('web.user_center.recharge_record',compact('data', 'links', 'query'));
    }

    /**
     * 收支明细
     * 
     * 
     * @param  Request $result [description]
     * @return [type]          [description]
     */
    public function balanceOfPayments(Request $request){
        $user = User::user();
        $user->checkRole('User');
        $query = $request->only('startTime', 'endTime');

        $data = DB::table('trade_records')
                    ->where(function ($q)use ($user, $query){

                        $q->where('pay_user', $user->id);
                        //追加查询条件
                        if(!empty($query['startTime'])){
                            $q = $q->where('pay_time', '>=', $query['startTime']);
                        }

                        if(!empty($query['endTime'])){
                            $q = $q->where('pay_time', '<=', $query['endTime']);
                        }

                    })
                    ->orWhere(function($q)use ($user, $query){

                        $q->where('receive_user', $user->id);

                        //追加查询条件
                        if(!empty($query['startTime'])){
                            $q = $q->where('pay_time', '>=', $query['startTime']);
                        }

                        if(!empty($query['endTime'])){
                            $q = $q->where('pay_time', '<=', $query['endTime']);
                        }

                    })
                    ->select('sn', 'remarks','pay_time','pay_user', 'receive_user', 'money', 'user_balance', 'status', 'type');

        
        //分页
        $data = $data->orderBy('pay_time','desc')->paginate(6);

        // dd($data);
        //获取分页链接
        $links = (new BoosstrapPageUser($data))->render();

        return view('web.user_center.balance_of_payments',compact('data', 'links', 'query'));
    }

    /**
     * 提现记录
     * 
     * @return [type] [description]
     */
    public function presentRecord(Request $request){
        $user = User::user();
        $user->checkRole('User');
        $query = $request->only('status','startTime','endTime');

        //查询充值记录
        $data = DB::table('trade_records')
                ->where('pay_user', $user->id)
                ->where('type', 5)
                ->select('sn', 'pay_time', 'card_number', 'money', 'status','created_at');

        //追加查询条件
        if(!empty($query['status'])){
            if($query['status'] == 'Y'){
                $data = $data->where('status', '1');
            }elseif($query['status'] == 'N'){
                $data = $data->where('status', '0');
            }else{
                $data = $data->where('status', '-1');
            }
        }

        if(!empty($query['startTime'])){
            $data = $data->where('created_at', '>=', $query['startTime']);
        }

        if(!empty($query['endTime'])){
            $data = $data->where('created_at', '<=', $query['endTime']);
        }

        //分页
        $data = $data->paginate(6);
        //获取分页链接
        $links = (new BoosstrapPageUser($data))->render();

        return view('web.user_center.present_record',compact('data', 'links', 'query'));
    }

    /**
     * 待收款明细
     * 
     * @return [type] [description]
     */
    public function generationCollection(Request $request){
        $user = User::user();
        $user->checkRole('User');
        $query = $request->only('startTime', 'endTime');


        $data = DB::table('project_profits as a')
                    ->leftJoin('projects as b', 'a.project_id', '=', 'b.id')
                    ->leftJoin('codes as c', 'b.repayment', '=', 'c.code')
                    ->where('a.type', 1)
                    ->where('a.status',0)
                    ->where('a.user_id', $user->id)
                    ->select('b.projects_name', 'c.name', 'a.input_time', 'a.money', 'a.profit', 'b.id')
                    ->orderBy('a.input_time','desc');

        //追加查询条件
        

        if(!empty($query['startTime'])){
            $data = $data->where('a.input_time', '>=', $query['startTime']);
        }

        if(!empty($query['endTime'])){
            $data = $data->where('a.input_time', '<=', $query['endTime']);
        }
        
        $data = $data->paginate(6);

        //查询待还款笔数 预期收款金额 预期本金
        $resources = DB::table('project_profits')
            ->where('user_id', $user->id)
            ->where('type' , 1)
            ->where('status', '0');
        //追加查询条件
        

        if(!empty($query['startTime'])){
            $resources = $resources->where('input_time', '>=', $query['startTime']);
        }

        if(!empty($query['endTime'])){
            $resources = $resources->where('input_time', '<=', $query['endTime']);
        }

        $resources = $resources->select(DB::raw('count(id) as count, sum(profit) as sumProfit, sum(money) as sumMoney'))->first();       

        $links = (new BoosstrapPageUser($data))->render();
        return view('web.user_center.generation_collection',compact('data', 'links', 'query', 'resources'));
    }

    /**
     * 已收款
     * 
     * @return [type] [description]
     */
    public function alreadyCollection(Request $request){
        $user = User::user();
        $user->checkRole('User');
        $query = $request->only('startTime', 'endTime');


        $data = DB::table('project_profits as a')
                    ->leftJoin('projects as b', 'a.project_id', '=', 'b.id')
                    ->leftJoin('codes as c', 'b.repayment', '=', 'c.code')
                    ->where('a.type', 1)
                    ->where('a.status', '<>', 0)
                    ->where('a.user_id', $user->id)
                    ->select('b.projects_name', 'c.name', 'a.pay_time', 'a.money', 'a.profit', 'b.id')
                    ->orderBy('a.pay_time','desc');

        //追加查询条件

        if(!empty($query['startTime'])){
            $data = $data->where('a.pay_time', '>=', $query['startTime']);
        }

        if(!empty($query['endTime'])){
            $data = $data->where('a.pay_time', '<=', $query['endTime']);
        }
        
        //TODO
        $data = $data->paginate(6);

         //查询待还款笔数 预期收款金额 预期本金
        $resources = DB::table('project_profits')
            ->where('user_id', $user->id)
            ->where('type' , 1)
            ->where('status', '<>', '0');
        //追加查询条件
        

        if(!empty($query['startTime'])){
            $resources = $resources->where('input_time', '>=', $query['startTime']);
        }

        if(!empty($query['endTime'])){
            $resources = $resources->where('input_time', '<=', $query['endTime']);
        }

        $resources = $resources->select(DB::raw('count(id) as count, sum(profit) as sumProfit, sum(money) as sumMoney'))->first();    

        $links = (new BoosstrapPageUser($data))->render();
        return view('web.user_center.already_collection',compact('data', 'links', 'query', 'resources'));
    }

    /**
     * 投资项目
     * 
     * @return [type] [description]
     */
    public function investmentProjects(Request $request,int $type = 0){
        $user = User::user();
        $user->checkRole('User');



        $query = DB::table('projects_user as a')
                    ->leftJoin('projects as b', 'a.projects_id', '=', 'b.id')
                    ->leftJoin('codes as c', 'b.status', '=', 'c.code')
                    ->select('b.id', 'b.projects_name', 'a.invest_money', 'a.expected_return', 'a.invest_time', 'b.trade_repayment_date', 'b.trade_finish_date', 'c.name', 'b.projects_file', 'b.status')
                    ->where('a.user_id', $user->id);


        switch ($type) {
            case 1:
                    $query = $query->where('b.status', 'rush');
                break;
            case 2:
                    $query = $query->where('b.status', 'payment');
                break;
            case 3:
                    $query = $query->where('b.status', 'finish');
                break;
            case 4:
                    $query = $query->where('b.status', 'full');
                break;
            
            default:
                # code...
                break;
        }
        
        $data = $query->orderBy('a.invest_time', 'desc')
                    ->paginate(6);

        //查询用户的代收本金/除去红包,红包算奖励金
        $dsMoney = 
                (
                    DB::table('project_profits')
                        ->where('type', 1)
                        ->where('status', 0)
                        ->where('user_id', $user->id)
                        ->select(DB::raw('sum(money) as dsMoney'))
                        ->first()
                )->dsMoney;

        //查询用户代收利息
        $dslx =
                (
                    DB::table('project_profits')
                        ->where('type', 1)
                        ->where('status', 0)
                        ->where('user_id', $user->id)
                        ->select(DB::raw('sum(profit) as dslx'))
                        ->first()
                )->dslx;

        //查询用户以赚利息
        $yslx =
                (
                    DB::table('project_profits')
                        ->where('type', 1)
                        ->where('status', '<>', 0)
                        ->where('user_id', $user->id)
                        ->select(DB::raw('sum(profit) as yslx'))
                        ->first()
                )->yslx;

        //查询用户红包奖励
        $hbMoney = 
                (
                    DB::table('gift_receives')
                        ->where('status', 1)
                        ->where('user_id', $user->id)
                        ->select(DB::raw('sum(money) as hbMoney'))
                        ->first()
                )->hbMoney;

                // dd($data);
                // 

        $links = (new BoosstrapPageUser($data))->render();

        return view('web.user_center.investment_projects', compact('data', 'links', 'dsMoney', 'dslx', 'yslx', 'hbMoney', 'type'));
    }

    /*-----------------------用户认证------------------------------*/

    /**
     * 修改用户密码
     * 
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function modifyPassword(ModifyPasswordRequest $request){

        //处理原密码
        //处理新密码
        $old_password = md5($request->input('old_password'));
        $new_password = bcrypt(md5($request->input('new_password')));

        //查询当前用户的原密码是否正确
        $user = User::findOrFail(User::user()->id);
        if(!(Hash::check($old_password, $user->password))){
            return $this->responseAjax(false,[["原密码错误"]]);
        }

        //修改密码
        $user->password = $new_password;
        $user->save();

        return $this->responseAjax(true,[['密码修改成功']]);
    }

    /**
     *  用户实名
     * 
     * @param Request $request [description]
     */
    public function setName(SetNameRequest $request){
        DB::beginTransaction();
        try {
            //获取请求参数
            $query = $request->only('name', 'id_card');
            $query['name_verified'] = 1;                    //设置已实名认证
            $user = User::findOrFail(User::user()->id);
            $user->userInfo->update($query);

            //sina实名认证
            $args['real_name'] = $query['name'];
            $args['cert_no'] = $query['id_card'];
            $args['identity_id'] = $user->identity_id;
            
            $result = SetRealName::send($args);
            if($result['response_code']!='APPLY_SUCCESS'){
                DB::rollBack();
                return $this->responseAjax(false,[[$result['response_message']]]);
            }
            DB::commit();
            return $this->responseAjax(true,[['用户实名认证成功']]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }
    public function setPhoneNumber(SetPhoneNumberRequest $request){
        //校验验证码
        $user = User::findOrFail(User::user()->id);


        if($user->userInfo->name_verified == 0)
            return $this->responseAjax(false,[['必须先实名认证']]);

        $phone_number = $request->input('phone_number');
        if($request->input('captcha') != Cache::get($phone_number)){
            return $this->responseAjax(false,[['验证码不正确']]);
        }else{
            //移除验证码
            Cache::forget($phone_number);
        }

        DB::beginTransaction();
        try{
            //修改用户手机号
            if($user->phone_number_verified == 1){
                return $this->responseAjax(false,[['当前用户手机已经绑定过了']]);
            }

            if(User::where('phone_number', $phone_number)->exists()){
                return $this->responseAjax(false,[['当前手机号已经被绑定']]);
            }

            $user->phone_number = $phone_number;
            $user->phone_number_verified = 1;
            $user->save();

            $result = BindingVerify::send(['identity_id' => $user->identity_id, 'identity_type' => 'UID', 'verify_entity' => $phone_number, 'verify_type' => 'MOBILE' ]);
            if($result['response_code'] != 'APPLY_SUCCESS'){
            return $this->responseAjax(false,[[$result['response_message']]]);
            }


            DB::commit();
            return $this->responseAjax(true,[['绑定手机成功']]);
        }catch(Exception $e){
            DB::rollBack();
        }
    }

    public function unBindPhoneNumber(SetPhoneNumberRequest $request){

        $user = User::user();
        $phone_number = $request->input('phone_number');

        if($request->input('captcha') != Cache::get($phone_number)){
            return $this->responseAjax(false,[['验证码不正确']]);
        }else{
            //移除验证码
            Cache::forget($phone_number);
        }

        DB::beginTransaction();
        try{
            //修改用户手机号
            if($user->phone_number_verified == 0){
                return $this->responseAjax(false,[['当前用户手机还未绑定']]);
            }

            if($phone_number != $user->phone_number){
                return $this->responseAjax(false,[['用户手机号不正确']]);
            }

            $user = User::findOrFail($user->id);
            $user->phone_number = null;
            $user->phone_number_verified = 0;
            $user->save();


            $result = UnbindingVerify::send(['identity_id' => $user->identity_id, 'identity_type' => 'UID', 'verify_type' => 'MOBILE' ]);
            if($result['response_code'] != 'APPLY_SUCCESS'){
            return $this->responseAjax(false,[[$result['response_message']]]);
            }


            DB::commit();
            return $this->responseAjax(true,[['解绑手机成功']]);
        }catch(Exception $e){
            DB::rollBack();
        }

    }

    /**
     * 发送验证码短信
     * 
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function sendPhoneCode(Request $request){
        //用户验证
        $user = User::user();
        //查询用户是否实名认证
        if($user->userInfo->name_verified == 0)
            return $this->responseAjax(false,[['必须先实名认证']]);

        $str = rand(100000, 999999);
            //取短信信息模板
            $message = Information::where('type', 'information_sms')//短信模板
            ->where('position', '=', 'sms_address_code')//验证码位置的短信模板
            ->where('state', 1)//启用
            ->first();
            //合成短信
            $to_message = str_replace('{code}', $str, $message->content);
            $result=phone_code($request->input('phone_number'),$to_message);
            Cache::put($request->input('phone_number'), $str, 5);
            return '验证码发送成功';
    }

    /**
     * 发送邮件验证码
     * 
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function sendEmailLink(Request $request){
        $email = $request->input('email');

        if(User::where('email', $email)->exists()){
            return $this->responseAjax(false, [["邮箱已经被注册"]]);
        }

        $user = User::user();

        //邮件内容模板
        $information = Information::where('type', 'information_email')
            ->where('position', 'email_validate_code')
            ->where('state', 1)
            ->first();
        //获取用户名
        $username = empty($user->userInfo->name) ? $user->username : $user->userInfo->name;

        $md5_email = md5('email');      //邮箱密文
        $time = microtme_format('Ymdmisx'); //当前时间戳
        //生成验证url
        $link = config('p2pdefault.web.http').'://'.$_SERVER['SERVER_NAME'].'/utils'.'/bind_email/'.$md5_email.'/'.$time;
        //替换模板内容
        $content = str_replace('{user}', $username, $information->content);
        $content = str_replace('{link}', $link, $content);

        $fa_data['content']=$content;
        $fa_data['email']=$email;
        $fa_data['title']=$information->title;

        $data['time'] = $time;
        $data['email']= $email;
        $data['uid'] = $user->id;

        Cache::put($md5_email,$data,30);   

        if(sendEmail($fa_data))
            return $this->responseAjax(true,[['邮件发送成功,请去收件箱验证....']]);
        else
            return $this->responseAjax(false,[['邮件发送失败,请重试...']]);
    }

    /**
     * 设置支付密码
     */
    public function setPayPassword(){
        //获取用户
        $user = User::findOrFail(User::user()->id);
        
        if($user->userInfo->name_verified == 0)
            return abort(600,'必须先实名认证');

         if($user->phone_number_verified == 0)
            return abort(600,'必须先绑定手机号码');

         if(empty($user->userInfo->bank_card_number))
            return abort(600,'必须先绑定银行卡');

        $result = QueryIsSetPayPassword::send(['identity_id'=> $user->identity_id, 'identity_type' => 'UID']);

        if($result['response_code'] != 'APPLY_SUCCESS'){
            return abort(600,$result['response_message']);
        }

        if($result['is_set_paypass'] == 'Y'){
            return abort(600, '已经设置过支付密码');
        }

        //设置支付密码
        $result = setPayPassword::send(['identity_id' => $user->identity_id,'identity_type'=>'UID','return_url'=>config('p2pdefault.web.http').'://'.$_SERVER['SERVER_NAME'].'/user/center?menu=1']);
         if($result['response_code'] != 'APPLY_SUCCESS'){
             abort(600,$result['response_message']);
         }

         return redirect($result['redirect_url']);
    }

    /**
     * [跳转至绑定银行卡页面]
     */
    public function setBank(){
        //用户验证
        $user = User::user();
        //查询用户是否实名认证
        if($user->userInfo->name_verified == 0)
            abort(600,'必须先实名认证');

        if($user->phone_number_verified == 0)
            abort(600,'必须先绑定手机号码');

        if(!empty($user->userInfo->bank_card_number))
            return abort(600,'已经绑定过银行卡了');
        
        return view('web.user_center.user_set_bank');
    }

    /**
     * 绑定银行卡
     */
    public function bindingBankCard(BindingBankCardRequest $request){
        $user = User::user();

        if(!empty($user->userInfo->bank_card_number))
            return $this->responseAjax(false,[['已经绑定过银行卡了']]);
        
        //生成请求订单号   
        $request_no = microtme_format('Ymdmisx');
        $args = [
                "request_no" => $request_no,
                "identity_id" => $user->identity_id,
                "identity_type" => "UID",
                "bank_code" => $request->input('bank_code'),
                "bank_account_no" => $request->input('bank_account_no'),
                "card_type" => "DEBIT",
                "card_attribute" => "C",
                "province" => $request['province'],
                "city" => $request->input('city'),
                "verify_mode" => "SIGN",
                "phone_no" => $request->input('phone_no'),
            ];

        $result = BindingBankCard::send($args);

        if($result['response_code'] != 'APPLY_SUCCESS'){
            return $this->responseAjax(false,[[$result['response_message']]]);

        }else{
            $data['bank_code'] = $request->bank_code;
            $data['ticket'] = $result['ticket'];
            $data['bank_account_no'] = $request->input('bank_account_no');
            //保存ticket
            Cache::put('bbc'.$user->identity_id,$data,15);
            return $this->responseAjax(true,[['验证码发送成功']]);
        }
    }

    /**
     * 绑定银行卡推进
     * 
     * @param  BindingBankCardRequest $request [description]
     * @return [type]                          [description]
     */
    public function bindingBankCardAdvance(BindingBankCardRequest $request){
        $user = User::user();
        //找到缓存中的ticket
        if(!Cache::has('bbc'.$user->identity_id)){
            abort(600,'验证码已经失效...');
        }
        $data = Cache::pull('bbc'.$user->identity_id);
        $result = BindingBankCardAdvance::send([
            'ticket' => $data['ticket'],
            'valid_code' => $request->input('valid_code'),
            ]);

        if($result['response_code'] == 'APPLY_SUCCESS' && $result['is_verified'] == 'Y'){
                //保存用户绑定的银行卡
                $user = User::findOrFail($user->id);
                $user->userInfo->bank_card_number = $data['bank_account_no'];
                $user->userInfo->bank_code = $data['bank_code'];
                $user->userInfo->bank_card_id = $result['card_id'];
                $user->userInfo->save();
                //跳转用户中心
                return redirect(action('UserCenter\UserCenterController@index'));
                // return ;
        }else{
            abort(600,$result['response_message']);
        }
    }

    /**
     * 解绑用户的银行卡
     * 
     * @return [type] [description]
     */
    public function unbindingBankCard(){
        $user = User::user();
        
        if(!$user->isBindingBankCard()){
            $this->responseAjax(false,[['用户没有绑定的银行卡']]);
        }

        $result = UnbindingBankCard::send([
                'identity_id' => $user->identity_id,
                'identity_type' => 'UID',
                'card_id' => $user->userInfo->bank_card_id,
                'advance_flag' => 'Y', 
            ]);

        if($result['response_code'] != 'APPLY_SUCCESS'){
            return $this->responseAjax(false,[[$result['response_message']]]);
        }

        $data['ticket'] = $result['ticket'];

        Cache::put('ubc'.$user->identity_id,$data,15);

        return $this->responseAjax(true,[['发送验证码成功']]);
    }

    /**
     * 解绑银行卡推进
     * 
     * @param  UnbindingBankCardRequest $reques [description]
     * @return [type]                           [description]
     */
    public function unbindingBankCardAdvance(UnbindingBankCardRequest $request){
        $user = User::user();

        if(!Cache::has('ubc'.$user->identity_id))
            return $this->responseAjax(false,[['验证已经失效']]);

        $data = Cache::get('ubc'.$user->identity_id);

        DB::beginTransaction();
        try{

            $user->userInfo->bank_code = '';
            $user->userInfo->bank_card_number = '';
            $user->userInfo->bank_card_id ='';
            $user->userInfo->save();

            $result = UnbindingBankCard::send([
                    'ticket' => $data['ticket'],
                    'service' => 'unbinding_bank_card_advance',
                    'identity_id' => $user->identity_id,
                    'identity_type' => 'UID',
                    'valid_code' => $request['valid_code'],
                ]);

            if($result['response_code'] != 'APPLY_SUCCESS')
                return $this->responseAjax(false,[[$result['response_message']]]);

            DB::commit();
            return $this->responseAjax(true,[['解绑银行卡成功']]);

        }catch(Exception $e){
            DB::rollBack();
        }
    }

    public function modifyPayPassword(){
        $user = User::user();

        $result = ModifyPayPassword::send([
            'identity_id' => $user->identity_id,
            'identity_type' => 'UID',
            ]);

        if($result['response_code'] != 'APPLY_SUCCESS')
            abort(600,$result['response_message']);

        return redirect($result['redirect_url']);
    }

    public function findPayPassword(){
        $user = User::user();

        $result = FindPayPassword::send([
            'identity_id' => $user->identity_id,
            'identity_type' => 'UID',
            ]);

        if($result['response_code'] != 'APPLY_SUCCESS')
            abort(600,$result['response_message']);

        return redirect($result['redirect_url']);
    }

    public function modifyVerifyMobile(){
        $user = User::user();

        $result = ModifyVerifyMobile::send([
            'identity_id' => $user->identity_id,
            'identity_type' => 'UID',
            ]);

        if($result['response_code'] != 'APPLY_SUCCESS')
            abort(600,$result['response_message']);
        // User::loginOut();
        return redirect($result['redirect_url']);
    }

    /**
     * 处理ajax异步请求错误消息返回
     * 
     * @param  bool   $resultStatus [true 正确 false 错误]
     * @param  array $json_msg     [json格式消息]
     * @return [type]               [description]
     */
    protected function responseAjax(bool $resultStatus, array $json_msg = []){
        return (new Response(json_encode($json_msg), $resultStatus?200:422))
              ->header('Content-Type', "application/json");
    }

    /**
     * 角色校验
     * 
     * @return boolean [description]
     */
    protected function checkRole(string $role){
        if(!User::user()->hasRole($role))
            return abort(404);
    }

    /**
     * 充值
     * @return [type] [description]
     */
    public function recharge(){
        $user=User::user();
	    //未实名认证、未绑定银行卡
	    if(!$user->userInfo->name_verified || empty($user->userInfo->bank_card_id)){
	        return redirect('user/settings')->withErrors('未实名认证或未绑定银行卡');
	    }
        $user->card_name=Code::findByCodeAndTypeId($user->userInfo->bank_code,'bank_code')->name;
        return view('web.user_center.recharge',compact('bind_card','user'));
    }
    public function doRecharge(Request $q){
        $money=$q->input("money");
        $user=User::user();
        $sn=createSn();
        $remarks='账户充值';
        $user_fee=0;//用户手续费
        $stage_fee=0;//平台手续费
        //判断是否机构用户
        if($user->hasRole(['OperatingPlatform','GuaranteeAgency','MarketingAgency'])){
            $lv=explode(',',Code::where(['code'=>'org_pot_recharge'])->value('description'));
        }else{
            //投资人手续费率
            if($user->hasRole('User')){
                $lv=explode(',',Code::where(['code'=>'user_pot_recharge'])->value('description'));
            }
            //融资人手续费率
            if($user->hasRole('Loaner')){
            	$lv=explode(',', Code::where(['code'=>'service_pot_recharge'])->value('description'));
            }
        }
        $data=[
            'out_trade_no'=>$sn,
            'summary'=>$remarks,
            'identity_id'=>$user->identity_id,
            'identity_type'=>'UID',
            'amount'=>$money,
            'pay_method'=>'online_bank^'.$money.'^SINAPAY,DEBIT,C',
            'account_type'=>'SAVING_POT',
            'return_url'=>config('sinapay.notify_url').'/user/center?navigation_id=1&menu=1',
        ];
        $total_fee=$money*($lv[1]+$lv[0])/100;
        $user_fee=$money*$lv[1]/100;
        //手续费默认0.01
        if($user_fee>0 && $user_fee<0.01){
            $user_fee=0.01;
        }
        if($total_fee>0 && $total_fee<0.01){
            $total_fee=0.01;
        }
        $stage_fee=$total_fee-$user_fee;
        $user_fee=round($user_fee,2);
        $stage_fee=round($stage_fee,2);
        //用户手续费必须大于0
        if($user_fee>0){
            $data['user_fee']=$user_fee;
        }
        //添加充值记录
        TradeRecords::insert([
            'sn'=>$sn,
            'type'=>4,
            'remarks'=>$remarks,
            'pay_user'=>$user->id,
            'money'=>$money,
            'fee_money'=>$stage_fee,
            'user_fee'=>$user_fee,
            'created_at'=>date('Y-m-d H:i:s')
        ]);
        return CreateHostingDeposit::send($data);
    }
    /**
     * 提现
     * @return [type] [description]
     */
    public function withdraw(){
        $user=User::user();
        //未实名认证、未绑定银行卡
        if(!$user->userInfo->name_verified || empty($user->userInfo->bank_card_id)){
            return redirect('user/settings');
        }
        $user->card_name=Code::findByCodeAndTypeId($user->userInfo->bank_code,'bank_code')->name;
        $sina_balance=$user->queryBalance();//新浪余额
        return view('web.user_center.withdraw',compact('sina_balance','bind_card'));
    }
    public function doWithdraw(Request $q){
        $money=$q->input("money");
        $money=round($money,2);
        if($money==0){abort(600,'请输入正确格式的金额');}
        $user=User::user();
        $sn=createSn();
        $remarks='账户提现';
        $user_fee=0;//用户手续费
        $stage_fee=0;//平台手续费
        //判断是否机构用户
        if($user->hasRole(['OperatingPlatform','GuaranteeAgency','MarketingAgency'])){
            $lv=explode(',',Code::where(['code'=>'org_pot_withdraw'])->value('description'));
            $user_fee=round($lv[1]*$money,2);
            $stage_fee=$lv[0]*$money;
        }else{
            //投资人手续费率
            if($user->hasRole('User')){
                $lv=explode(',',Code::where(['code'=>'user_pot_withdraw'])->value('description'));
            }
            //融资人手续费率
            if($user->hasRole('Loaner')){
                $lv=explode(',',Code::where(['code'=>'service_pot_withdraw'])->value('description'));
            }
            $user_fee=$lv[1];
            $stage_fee=$lv[0];
        }
        $data=[ 
            'out_trade_no'=>$sn,
            'summary'=>$remarks,
            'identity_id'=>$user->identity_id,
            'identity_type'=>'UID',
            'amount'=>$money,
            'pay_method'=>'online_bank^'.$money.'^SINAPAY,DEBIT,C',
            'account_type'=>'SAVING_POT',
            'return_url'=>config('sinapay.notify_url').'/user/center?navigation_id=1&menu=1',
        ];
        if($user_fee>0 && $user->hasRole('Loaner')){
            $data['user_fee']=$user_fee;
        }
        //添加提现记录
        TradeRecords::insert(['sn'=>$sn,'type'=>5,'remarks'=>$remarks,'pay_user'=>$user->id,'money'=>$money,
        	'fee_money'=>$stage_fee,'user_fee'=>$user_fee,'created_at'=>date('Y-m-d H:i:s')]);
        return CreateHostingWithdraw::send($data);
    }

    /**
     * 打印项目合同
     * 
     * @param  int    $id [description]
     * @return [type]     [description]
     */
    public function printTemplate(int $id){
        //查询当前id对应的项目合同
        $tmp = (DB::table('projects')->where('id',$id)->select('projects_file as tmp')->first())->tmp;
        
        if(empty($tmp)){
            abort(600,'找不到一份合同');
        }

        return view('web.user_center.template',compact('tmp'));
    }
    /**
     * 显示存钱罐协议
     * 
     * @return [type] [description]
     */
    public function piggyBankAgreement(){
        $article = Article::where('id', config('p2pdefault.web.piggy_bank_agreement_id'))->first();
        return view('web.user_center.piggy_bank_agreement' , compact('article'));
    }
    /**
     * 新浪支付使用协议
     * 
     * @return [type] [description]
     */
    public function sinaPaymentProtocol(){
        $article = Article::where('id', config('p2pdefault.web.sina_payment_protocol_id'))->first();
        return view('web.user_center.sina_payment_protocol', compact('article'));
        
    }
    /**
     * 用户基本户转入存钱罐
     * 
     * @param  int    $id [description]
     * @return [type]     [description]
     */
    public function transferToSavingPot(int $id){
        //
        $user = User::findOrFail($id);

        $available_balance = $user->basicMoney();
        
        if($available_balance<= 0){
            return "基本户没有余额余额！";
        }

        $data = [
            'out_trade_no' => 'order'.microtme_format('YmdHisx'),
            'payer_identity_id' => $user->identity_id,
            'payer_identity_type' => 'UID',
            'payer_account_type' => 'BASIC',
            'payee_identity_id' => $user->identity_id,
            'payee_identity_type' => 'UID',
            'payee_account_type' => 'SAVING_POT',
            'amount' => $available_balance,
            'summary' => '由基本户自动转入存钱罐',
            'transfer_mode' => 'CASHDESK',
            'return_url' => 'https://' . $_SERVER['SERVER_NAME'] .'/user/settings?nemu = 0',
        ];


        $result = CreateHostingTransfer::send($data);


        // dd($result);

        // dd($result);
        return $result;
    }
    public function getBankInfo(Request $request){
        $bank_code = $request->input('bank_code');

        //查询数据字典表
        $bank_info = DB::table('codes')
                    ->where('type_id', 'bank_code')
                    ->where('code',$bank_code)
                    ->first();

        if(!$bank_info){
            return $this->responseAjax(false,[['没有找到该银行信息']]);
        }

        // dd($bank_info);
        return $this->responseAjax(true,[$bank_info->description]);
    }

}   